import cCalendar from "components/calendar";
import { Image as VanImage ,Dialog} from 'vant';
import AMap from "AMap";
export default {
  data() {
    return {
      type: null,
      point: {},

      current_date: "",//当前日期（没选中日期时）
      startTime: "00:00",
      endTime: "00:00",
      start_time: "",//有效期开始时间
      end_time: "",//有效期结束时间
      options: {
        header_font_color: "#4978F8",
        selected_bg_color: "#4978F8",
        disabled_font_color: "#ccc",
        today_font_color: "#4978F8",
        pre_month_color: "#4978F8",
        next_month_color: "#4978F8",
      },
      showCalendar: false,
      calendarEvents: [],

      categoryShow: false,
      radio: "",
      finish_at:"",
      start_at:"",


      district: district, // 地址本地数据
      addressName: "",
      addressShow: false,
      strShow: false,
      streetShow: false,
      address_form: {
        province: "",
        city: "",
        district: "",
        street: "",
        address: ""
      },
      districtVal: [],//街道数据
      province_id: "",
      city_id: "",
      district_id: "",
      street_id: "",


      category_name: "",
      form: {
        locationTitle: "",
        category_id: "",
        cost: "",
        loaction: "",
        name: "",
        content: "",
        timer: "",
        info_indate: "",//信息有效期
      },


      service_fee: "",
      title: "",
      content: "",
      address: "",
      realname: "",

      time_type: "",
      valid_time: "",
      list: [],
      tips_list: [],
      show_skill_flag: false,

      demand_id: "",
      order_id: "",
      member_src:"",
      member_id: "",//师傅id

      is_keep:1,
      reason:"",
    };
  },
  async activated() {

    if(this.is_keep == 1){
      this.init();
    }

    this.type = this.$route.params.type;//1-发布需求、2-查看需求
    if (this.$route.params.type == 2 && this.$route.params.demand_id) {
      this.demand_id = this.$route.params.demand_id;
      this.get_detail();
    } else {
      await this.check_apply();//判断是否申请
      this.getCategoryData();
      if (localStorage.getItem('myLocation')) {
        let myLocation = JSON.parse(localStorage.getItem('myLocation'));
        this.point = myLocation.point;
        this.form.locationTitle = myLocation.address;
      } else {
        this.ready();
      }
    }
  },
  methods: {
    submit_again(){
        Dialog.confirm({
          message: '请确认是否重复发布',
        })
          .then(() => {
            this.submit();
          })
          .catch(() => {
          });
    },
    async check_apply(){
    let {result,msg,data} =  await $http.get("plugin.be-within-call.frontend.role-apply.detail",{role:1},'');
      if(result){
        if(data.apply_status!==1){
          this.$router.push(this.fun.getUrl("anytimeRoleApply",{apply_for_type: 1 }))
        }
      }else{
        this.$toast(msg);
      }
    },
    init() {
      this.start_at = '';
      this.finish_at = '';
      this.is_reject = null;
      this.reason = '';
      this.member_src = "";
      this.address_form = {
        province: "",
        city: "",
        district: "",
        street: "",
        address: ""
      };
      this.streetShow = false;
      this.category_name = "";
      this.tips_list = [];
      this.title = "";
      this.content = "";
      this.service_fee = "";
      this.form.info_indate = "";
      this.address_form.street = '';
      this.addressName = '';
      this.form.locationTitle = "";
      this.realname = "";
      this.order_id = '';
      this.show_skill_flag = false;
      this.member_id = '';
      this.form.timer = "";
      this.address = "";
    },
    getAmap(city, lng, lat) {
      AMap.plugin("AMap.Geocoder", () => {
        var geocoder = new AMap.Geocoder({ city });
        geocoder.getAddress([lng, lat], (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            // result为对应的地理位置详细信息
            this.form.locationTitle = result.regeocode.formattedAddress
          }
        })
      })
    },
    input() {
      $http.get('plugin.be-within-call.frontend.public-search.easy-shi-fu', { kwd: this.realname }, '').then(res => {
        if (res.result) {
          this.tips_list = res.data;
          this.show_skill_flag = true;
        }
      })
    },
    choose_handle(data) {
      this.member_id = data.member_id;
      this.member_src = data.personal_pic;
      this.realname = data.realname;
      this.show_skill_flag = false;
    },
    get_detail() {
      $http.get('plugin.be-within-call.frontend.publish.need-detail', { id: this.demand_id }, '').then(res => {
        if (res.result) {
          let data = res.data;
          if(data.apply_status==-11){
            this.type=1;
          }
          this.reason = data.reason;
          this.title = data.title;
          this.content = data.content;
          this.service_fee = data.service_fee;
          this.addressName = `${data.province_name} ${data.city_name} ${data.district_name}`;
          this.address_form.street = data.street_name;
          this.address = data.address;
          this.category_name = data.has_one_category.title || '';
          this.realname = data.has_one_shifu && data.has_one_shifu.realname || '';
          this.form.timer = data.start_time_str + '-' + data.finish_time_str;
          this.form.info_indate = data.valid_time;
          this.order_id = data.order_id;
          this.point = {
            lng:data.longitude,
            lat:data.latitude,
          }

          this.address_form.province= data.province_name;
          this.address_form.city= data.city_name;
          this.address_form.district= data.district_name;
          this.address_form.street = data.street_name;
          this.province_id= data.province_id;
          this.city_id= data.city_id;
          this.district_id= data.district_id;
          this.street_id= data.street_id;
          this.radio= data.has_one_category.id;

          let _time = data.valid_time.split(" ")[0];
          this.start_at = new Date(data.start_at).getTime() / 1000 ;
          this.finish_at = new Date(data.finish_at).getTime() / 1000 ;
          this.valid_time = _time;

          this.getAmap(data.city_name, data.longitude, data.latitude);
        } else {
          this.$toast(res.msg)
        }
      })
    },
    confirm() {
      let arr = this.list.filter(item => {
        if (item.id == this.radio) {
          return item;
        }
      })
      this.category_name = arr[0].title;
      this.categoryShow = false;
    },
    getCategoryData() {
      $http.get("plugin.be-within-call.frontend.index.get-category-list", { sort_type: 1 }).then(res => {
        if (res.result) {
          this.list = res.data;
        } else {
          this.$toast(res.msg);
        }
      })
    },
    format_time(type) {

      let current_date = this.current_date.replace(/-/gi,'/');
      let time = "";
      if (type == 'start') {
        time = `${current_date} ${this.start_time[0]}:${this.start_time[1]}:00`;
      } else {
        time = `${current_date} ${this.end_time[0]}:${this.end_time[1]}:00`;

      }

      return new Date(time).getTime() / 1000;
    },
    show_order() {
      this.$router.push(
        this.fun.getUrl("anyOrderDetail", { type: "individual", order_id: this.order_id })
      );
    },
    submit() {
      let valid_time =this.valid_time.replace(/-/gi,'/');
      let json = {
        longitude: this.point.lng,
        latitude: this.point.lat,
        service_fee: this.service_fee,
        title: this.title,
        content: this.content,
        street: this.address_form.street,
        address: this.address,
        province: this.address_form.province,
        city: this.address_form.city,
        category_id: this.radio,
        district: this.address_form.district,
        province_id: this.province_id,
        city_id: this.city_id,
        district_id: this.district_id,
        street_id: this.street_id,
        valid_time: new Date(`${valid_time} 00:00:00`).getTime() / 1000,
        start_at:this.start_at||this.format_time('start'),
        finish_at:this.finish_at||this.format_time('end')
      };


      if (this.member_id) {
        json.shifu_uid = this.member_id;
      }
      $http.post("plugin.be-within-call.frontend.create-need.publish", json, '').then(res => {
        this.$toast(res.msg);
        if (res.result) {
          this.is_keep = 1;
          this.$router.push(this.fun.getUrl("orderpay", { order_ids: res.data.order_ids,}));
        }
      })
    },
    ready() {
      this.fun
        .getLocation()
        .then(res => {
          this.point = res.point;
          this.form.locationTitle = res.title;
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 日期补零
    zeroPad(n) {
      return String(n < 10 ? "0" + n : n);
    },
    change_start(picker) {
      let arr = []
      for (let i = 0; i < picker.$children.length; i++) {
        arr.push(picker.$children[i].currentIndex)
      }
      this.start_time = arr;
    },
    change_end(picker) {
      let arr = []
      for (let i = 0; i < picker.$children.length; i++) {
        arr.push(picker.$children[i].currentIndex)
      }
      this.end_time = arr;
    },
    validate_picker() {
      console.log(this.type);
      if (this.time_type == 'time') {
        if (this.start_time == '' || this.end_time == '') {
          return this.$toast("请选择时间")
        } else if ((this.start_time[0] > this.end_time[0]) || (this.start_time[0] == this.end_time[0] && this.start_time[1] > this.end_time[1])) {
          return this.$toast('开始时间不能小于结束时间')
        } else if (this.start_time[0] == this.end_time[0] && this.start_time[1] == this.end_time[1]) {
          return this.$toast('开始时间不能等于结束时间')
        }

        this.form.timer = `${this.current_date} ${this.zeroPad(this.start_time[0])}:${this.zeroPad(this.start_time[1])} 至 ${this.zeroPad(this.end_time[0])}:${this.zeroPad(this.end_time[1])}`;
        this.showCalendar = false;
      } else {
        this.form.info_indate = this.valid_time;
        this.showCalendar = false;
      }
    },
    close_calendar_popup() {
      this.validate_picker()
    },
    monthChanged(e) {  //移动月份
      if(this.time_type == 'time'){
        this.current_date = e;
      }else{
        this.valid_time = e;
      }
    },
    //定位
    toGeolocation() {
      this.is_keep = 2;
      this.$store.commit("setReferer", window.location.href);
      this.$router.push(this.fun.getUrl("o2oLocation_loc", { fromHome: 1 }));
    },
    show_calendar_popup(type) {
      this.time_type = type;
      this.showCalendar = true;
    },
    selectedDay(e) {
      let date = "";
      if (e.length >= 3) {
        date = e[0] + '-' + e[1] + '-' + e[2];
      }
      if (this.time_type == 'indate') {
        this.valid_time = date;
      }else{
        this.current_date = date;
      }
    },

    streetConfirm(item) {
      this.street_id = item.id;
      this.address_form.street = item.areaname;
      this.streetShow = false;
    },
    // 地址回调
    addressCallback(obj) {
      this.address_form.street = "";
      this.districtVal = [];
      this.addressName = obj.itemName1 + " " + obj.itemName2 + " " + obj.itemName3;
      this.address_form.province = obj.itemName1;
      this.address_form.city = obj.itemName2;
      this.address_form.district = obj.itemName3;

      this.province_id = obj.itemValue1;
      this.city_id = obj.itemValue2;
      this.district_id = obj.itemValue3;
      console.log(obj);
      this.getStreet(obj.itemValue3);
    },

    // 获取街道
    getStreet(param) {
      this.district_id = param;
      $http
        .get("member.memberAddress.street", {
          district_id: param
        }, '加载中')
        .then(response => {
          if (response.result === 1 && !this.fun.isTextEmpty(response.data)) {
            if (!this.fun.isTextEmpty(response.data) && response.data.length > 0) {
              this.districtVal = response.data;
              this.strShow = true;
            } else {
              this.strShow = false;
            }
          } else {
            this.strShow = false;
          }
        })
        .catch(error => {
          this.strShow = false;
          console.log(error);
        });
    },
  },
  components: { cCalendar, VanImage }
};